<?php
/**
 * 首页控制类
 * @author 大梦
 * @DateTime 2019/07/06
 */

namespace app\index\controller;

use think\Request;
use think\Validate;
use app\common\model\Staff as StaffModel;
use app\common\model\Banner as BannerModel;
use app\common\model\Weixin as WechatModel;
use app\common\model\VoteStaff as VoteStaffModel;
use app\common\model\VoteDetail as VoteDetailModel;
use app\common\model\VotePeriod as VotePeriodModel;

class Index extends Common
{

    /**
     * 优秀员工投票列表
     * @author Meng
     * @dateTime 2020-09-23
     * @return   [type]     [description]
     */
    public function index()
    {
        $params = input();

        $current_vote_id = '';
        $is_login = 0;
        $is_vote_all = 0;

        $member_id = 0;
        if (session('member_id')) {
            $is_login = 1;
            $member_id = session('member_id');
        }

        // 轮播
        $banner_list = (new BannerModel())->getBannerList();

        // 优秀员工列表
        $staff_list = [];

        $VoteStaffModel = new VoteStaffModel();

        if ($this->current_vote_info) {
            $current_vote_id = $this->current_vote_info['id'];
            $where_staff = [
                ['a.aid', 'eq', $current_vote_id],
                ['a.is_valid', 'eq', 1],
                ['a.is_del', 'eq', 0],
            ];
            $sql_where_detail = 'a.id = c.sid AND a.aid = c.aid AND c.uid = ' . $member_id;
            $staff_list = $VoteStaffModel->alias('a')
                ->join('staff b','a.sid = b.id', 'LEFT')
                ->join('vote_detail c', $sql_where_detail, 'LEFT')
                ->where($where_staff)
                ->field('a.id, a.sid, a.desc, a.profile_pic, a.score, c.score as v_score, b.nickname,
                    b.real_name, b.avatar, b.profile, c.sid as vid, a.create_time')
                ->order('a.id asc')
                ->select();
            $vote_count = 0;
            foreach ($staff_list as $key => $item) {
                if ($item['vid'] > 0) $vote_count++;
            }
            $is_vote_all = $vote_count == count($staff_list) ? 1 : 0;
        }

        $data = [
            'is_login' => $is_login,
            'staff_list' => $staff_list,
            'is_vote_all' => $is_vote_all,
            'banner_list' => $banner_list,
            'current_vote_id' => $current_vote_id,
        ];

        if (isset($params['is_debug'])) {
            dump($VoteStaffModel->getLastSql());
            halt($data);
        }

        $this->assign($data);
        return view();
    }

    /**
     * 投票页面
     * @author Meng
     * @dateTime 2020-12-08
     * @param    Request    $request [description]
     * @return   [type]              [description]
     */
    public function vote(Request $request)
    {

        $params = input();
        // 用户ID
        $uid = session('member_id') ?? '';
        // 员工ID
        $sid = $params['id'] ?? '';
        // 活动ID
        $aid = $params['aid'] ?? '';

        $data = [
            'uid' => $uid,
            'sid' => $sid,
            'aid' => $aid,
        ];
        $this->assign($data);

        return view();
    }

    /**
     * 提交投票信息
     * @author Meng
     * @dateTime 2020-12-08
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function submitVote()
    {
        $params = input();
        $member_id = session('member_id') ?? '';
        $exc_staff_id = $params['sid'] ?? '';
        $vote_id = $params['aid'] ?? '';
        $score = $params['score'] ?? 0;

        if (!$exc_staff_id || !$vote_id) {
            return $this->api_error('数据信息有误！', $params);
        }

        $VoteStaffModel = new VoteStaffModel();
        $VoteDetailModel = new VoteDetailModel();
        $where_detail = [
            ['is_del', 'eq', 0],
            ['aid', 'eq', $vote_id],
            ['uid', 'eq', $member_id],
            ['sid', 'eq', $exc_staff_id],
        ];
        $vote_info = $VoteDetailModel->where($where_detail)->find();
        if ($vote_info) {
            return $this->api_error('一人只能投票一次');
        }
        $insert_data = [
            'aid' => $vote_id,
            'uid' => $member_id,
            'sid' => $exc_staff_id,
            'score' => $score,
        ];
        $where_staff = [
            ['is_del', 'eq', 0],
            ['aid', 'eq', $vote_id],
            ['id', 'eq', $exc_staff_id],
        ];
        $update = $VoteStaffModel->where($where_staff)->setInc('score', $score);
        $new_vote = $VoteDetailModel->allowField(true)->save($insert_data);
        if ($new_vote && $update) {
            return $this->api_success('投票成功');
        }
        return $this->api_error('投票失败');
        
    }


    /**
     * 评选结果
     * @author Meng
     * @dateTime 2020-09-23
     * @return   [type]     [description]
     */
    public function vote_result()
    {
        $params = input();

        $current_vote_id = '';
        $is_login = 0;

        $member_id = 0;
        if (session('member_id')) {
            $is_login = 1;
            $member_id = session('member_id');
        }

        // 轮播
        $banner_list = (new BannerModel())->getBannerList();

        // 优秀员工列表
        $staff_list = [];

        $VoteStaffModel = new VoteStaffModel();

        if ($this->current_vote_info) {
            $current_vote_id = $this->current_vote_info['id'];
            $where_staff = [
                ['a.aid', 'eq', $current_vote_id],
                ['a.is_valid', 'eq', 1],
                ['a.is_del', 'eq', 0],
            ];
            $sql_where_detail = 'a.sid = c.sid AND a.aid = c.aid AND c.uid = ' . $member_id;
            $staff_list = $VoteStaffModel->alias('a')
                ->join('staff b','a.sid = b.id', 'LEFT')
                ->join('vote_detail c', $sql_where_detail, 'LEFT')
                ->where($where_staff)
                ->field('a.id, a.sid, a.profile_pic, a.score, c.score as v_score, b.nickname,
                    b.real_name, b.avatar, b.profile, c.id as vid, a.create_time')
                ->select();
        }

        $data = [
            'is_login' => $is_login,
            'staff_list' => $staff_list,
            'banner_list' => $banner_list,
            'current_vote_id' => $current_vote_id,
        ];

        if (isset($params['is_debug'])) {
            dump($VoteStaffModel->getLastSql());
            halt($data);
        }

        $this->assign($data);
        return view();
    }

    /**
     * 获取投票结果
     * @author Meng
     * @dateTime 2020-12-10
     * @return   [type]     [description]
     */
    public function get_vote_result()
    {
        $params = input();

        $current_vote_id = '';

        $VoteStaffModel = new VoteStaffModel();

        if (!$this->current_vote_info) {
            return $this->api_error('暂无评选信息');
        }

        $current_vote_id = $this->current_vote_info['id'];
        $where_staff = [
            ['a.aid', 'eq', $current_vote_id],
            ['a.is_valid', 'eq', 1],
            ['a.is_del', 'eq', 0],
        ];

        $vote_result = $VoteStaffModel->alias('a')
            ->join('staff b','a.sid = b.id', 'LEFT')
            ->where($where_staff)
            ->field('a.score')
            ->select();
        $score_array = [];
        foreach ($vote_result as $key => $item) {
            array_push($score_array, $item['score']);
        }
        return $this->api_success('查询成功', $score_array);
    }

    public function get_mobile()
    {


        $appid = 'wxfb202f07c0c5a94b';
        $secret = '8c6ce6d8f55c619c1306f46e1850959d';
        $params = input();

        $js_code = $params['js_code'] ?? '';

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxfb202f07c0c5a94b&secret=8c6ce6d8f55c619c1306f46e1850959d&js_code=' . $js_code . '&grant_type=authorization_code';
        $wx_data = get_by_curl($url);

        $sessionKey = $wx_data['session_key'];
        $iv = $params['iv'];
        $encryptedData = $params['encryptedData'];

        $data = '';
        $pc = new WechatModel($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );


        if ($errCode == 0) {
            return $this->api_success('获取成功', json_decode($data));
        } else {
            return $this->api_error('获取失败', $errCode);
        }

    }
}
